﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using hou_elearning.Entity;
using hou_elearning.Business;
using hou_elearning.Custom;

public partial class Controls_ucDanhsachkhoahoc : System.Web.UI.UserControl
{
    private List<KhoahocEntity> glbLstGrvDatasource = null;
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            napGrvDanhsachkhoahoc(true);
        }
    }
    /// <summary>
    /// Lấy ID người dùng đăng nhập
    /// </summary>
    /// <author>liemqv</author>
    /// <create>25/04/2010</create>
    /// 

    public Int32 iGetUserLogin()
    {
        Int32 PK_iNguoidungID = 0;
        try
        {
            if (Session["UserID"] != null)
            {
                PK_iNguoidungID = Int32.Parse(Session["UserID"].ToString());
            }
            else
            {
                Response.Redirect("~/Admin/Login.aspx?re=?page=Danhsachkhoahoc");
            }
        }
        catch(Exception ex)
        {
            PK_iNguoidungID = 0;
        }
        return PK_iNguoidungID;
    }

    /// <summary>
    /// Kiểm tra người dùng có nằm trong khóa học
    /// </summary>
    /// <param name="PK_iHocvienID">Int64:ID học viên</param>
    /// <author>liemqv</author>
    /// <create>25/04/2012</create>
    /// 
    public Boolean bNamtrongkhoahoc(Int64 PK_iHocvienID, Int64 PK_iKhoahocID)
    {
        Boolean bRes = false;
        List<Khoahoc_HocvienEntity> lstKhoahocHocvien = Khoahoc_HocvienBRL.GetByFK_iKhoahocID(PK_iKhoahocID);
        if(lstKhoahocHocvien.Find(delegate(Khoahoc_HocvienEntity oKhoahocHocvien){return oKhoahocHocvien.FK_iHocvienID == PK_iHocvienID;}) != null)
        {
            bRes = true;
        }
        return bRes;
    }

    /// <summary>
    /// Hiển thị danh sách các khóa học
    /// </summary>
    /// <author>liemqv</author>
    /// <create>25/04/2012</create>
    public void napGrvDanhsachkhoahoc(bool bLoadFromDB)
    {
        if (bLoadFromDB == true || Cache["cacheLstGrvDatasource"] == null)
        {
            glbLstGrvDatasource = KhoahocBRL.GetAll();
            Cache["cacheLstGrvDatasource"] = glbLstGrvDatasource;
        }
        glbLstGrvDatasource = (List<KhoahocEntity>)Cache["cacheLstGrvDatasource"];
        if (glbLstGrvDatasource.Count <= 0)
        {
            divThongbao.InnerHtml = "<p class='info' id='warning'><span class='info_inner'>Không có bản ghi nào để hiển thị!</span></p>";
        }
        else
        {
            if (Session["Khoahoccuatoi"] != null && Boolean.Parse(Session["Khoahoccuatoi"].ToString()) == true)
            {
                //Lấy danh sách khóa học mà người dùng đăng nhập tham gia
                List<Khoahoc_HocvienEntity> lstKhoahocHocvien = Khoahoc_HocvienBRL.GetByFK_iHocvienID(iGetUserLogin());
                List<KhoahocEntity> lstKhoahoccuatoi = new List<KhoahocEntity>();
                List<KhoahocEntity> lstKhoahocTmp = new List<KhoahocEntity>();
                foreach (Khoahoc_HocvienEntity oKhoahocHocvien in lstKhoahocHocvien)
                {
                    lstKhoahocTmp = glbLstGrvDatasource.FindAll
                    (
                        delegate(KhoahocEntity oKhoahocRes)
                        {
                            return (oKhoahocRes.PK_iKhoahocID == oKhoahocHocvien.FK_iKhoahocID);
                        }
                    );
                    if (lstKhoahocTmp.Count > 0)
                    {
                        lstKhoahoccuatoi.Add(lstKhoahocTmp[0]);
                    }
                }
                //Nạp grv
                grvDanhsachkhoahoc.DataSource = lstKhoahoccuatoi;
                lstKhoahocTmp = null;
                lstKhoahocHocvien = null;
            }
            else
            {
                grvDanhsachkhoahoc.DataSource = glbLstGrvDatasource;
            }
            grvDanhsachkhoahoc.DataKeyNames = new string[] { "PK_iKhoahocID" };
            grvDanhsachkhoahoc.DataBind();
        }
    }

    protected void grvDanhsachkhoahoc_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grvDanhsachkhoahoc.PageIndex = e.NewPageIndex;
        napGrvDanhsachkhoahoc(false);
    }
    protected void grvDanhsachkhoahoc_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if(e.CommandName == "Sort")
        {
            return;
        }
        int index = Convert.ToInt32(e.CommandArgument);
        GridViewRow row = grvDanhsachkhoahoc.Rows[index];
        Int64 PK_iKhoahocID = Int64.Parse(row.Cells[1].Text);
        LinkButton btnDangky = null;
        if (iGetUserLogin() > 0)
        {
            btnDangky = (LinkButton)row.Cells[8].Controls[0];
            KhoahocEntity oKhoahoc = KhoahocBRL.GetOne(PK_iKhoahocID);
            if (e.CommandName.Equals("Dangky"))
            {
                DangkykhoahocEntity oDangky = new DangkykhoahocEntity();
                oDangky.FK_iKhoahocID = PK_iKhoahocID;
                oDangky.FK_iHocvienID = iGetUserLogin();
                oDangky.iTrangthai = 0;
                oDangky.dNgaydangky = DateTime.Now;
                Int64 iNewDangkykhoahocID = 0;
                iNewDangkykhoahocID = DangkykhoahocBRL.Add(oDangky);
                if (iNewDangkykhoahocID > 0)
                {
                    btnDangky.CommandName = "Huydangky";
                    btnDangky.Text = "Hủy đăng ký";
                    btnDangky.CssClass = "button button-red";
                }
            }
            else
                if (e.CommandName.Equals("Huydangky"))
                {
                    DangkykhoahocEntity oDangky = DangkykhoahocBRL.GetByFK_iKhoahocIDAndFK_iHocvienID(PK_iKhoahocID, iGetUserLogin());
                    if(DangkykhoahocBRL.Remove(oDangky.PK_iDangkykhoahocID) == true)
                    {
                        btnDangky.CommandName = "Dangky";
                        btnDangky.Text = "Đăng ký";
                        btnDangky.CssClass = "button button-blue";
                    }
                }
            else
                if(e.CommandName.Equals("Vaolop"))
                {
                    Session["KhoahocID"] = PK_iKhoahocID;
                    Response.Redirect("~/lop-hoc");
                }
        }
        else
        {
            Response.Redirect(ResolveUrl("~/Admin/Login.aspx"));
        }
    }
    protected void grvDanhsachkhoahoc_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (ViewState["SortDirection"] == null)
            ViewState["SortDirection"] = "ASC";
        else
        {
            ViewState["SortDirection"] = ViewState["SortDirection"].ToString() == "ASC" ? "DESC" : "ASC";
        }
        List<KhoahocEntity> lstKhoahoc = (List<KhoahocEntity>)Cache["cacheLstGrvDatasource"];
        glbLstGrvDatasource = KhoahocEntity.Sort(lstKhoahoc, e.SortExpression, ViewState["SortDirection"].ToString());
        napGrvDanhsachkhoahoc(false);
    }
    protected void grvDanhsachkhoahoc_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        Label lblSoluonghocvien = null;
        Label lblChungchi = null;
        Label lblDanhgia = null;
        Label lblTrangthai = null;
        KhoahocEntity oKhoahoc = null;
        LinkButton btnDangky = null;
        ChungchiEntity oChungchi = null;
        HyperLink hplChitiet = null;
        long iID = 0;
        //Kiểm tra người dùng có trong khóa học hay không
        Int64 PK_iHocvienID = iGetUserLogin();

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            try
            {
                /* Lấy ID của hàng hiện tại */
                if (!e.Row.Cells[1].Text.Trim().Equals(""))
                {
                    iID = Int64.Parse(e.Row.Cells[1].Text.Trim());
                    oKhoahoc = KhoahocBRL.GetOne(iID);
                }
                lblChungchi = (Label)e.Row.FindControl("lblChungchi");
                if (lblChungchi != null)
                {
                    short FK_iChungchiID = short.Parse(lblChungchi.Text.Trim());
                    oChungchi = ChungchiBRL.GetOne(FK_iChungchiID);
                    lblChungchi.Text = oChungchi.sTenchungchi;
                }

                lblSoluonghocvien = (Label)e.Row.FindControl("lblSoluonghocvien");
                if (lblChungchi != null)
                {
                    Int64 PK_iKhoahocID = Int64.Parse(lblSoluonghocvien.Text.Trim());
                    List<DangkykhoahocEntity> lstDangkykhoahoc = DangkykhoahocBRL.GetByFK_iKhoahocID(PK_iKhoahocID);
                    List<Khoahoc_HocvienEntity> lstKhoahocHocvien = Khoahoc_HocvienBRL.GetByFK_iKhoahocID(PK_iKhoahocID);
                    lblSoluonghocvien.Text = (lstDangkykhoahoc.Count + lstKhoahocHocvien.Count) + "/" + oKhoahoc.iSoluongdukien;
                    lstKhoahocHocvien = null;
                    lstDangkykhoahoc = null;
                }

                lblDanhgia = (Label)e.Row.FindControl("lblDanhgia");
                if (lblDanhgia != null)
                {
                    lblDanhgia.Text = "Đang cập nhật...";
                }

                lblTrangthai = (Label)e.Row.FindControl("lblTrangthai");
                if (lblTrangthai != null)
                {
                    if(oKhoahoc.iTrangthai == 1)
                    {
                        lblTrangthai.ForeColor = System.Drawing.ColorTranslator.FromHtml("#D14836");
                        lblTrangthai.Text = "Đang học";
                    }
                    else
                        if(oKhoahoc.iTrangthai == 0)
                        {
                            if (GlobalFunction.iSodangkyConlai(oKhoahoc.PK_iKhoahocID) <= 0)
                            {
                                lblTrangthai.ForeColor = System.Drawing.ColorTranslator.FromHtml("#D14836");
                                lblTrangthai.Text = "Đã đủ học viên";
                            }
                            else
                            {
                                lblTrangthai.ForeColor = System.Drawing.ColorTranslator.FromHtml("#205AAF");
                                lblTrangthai.Text = "Đang mở";
                            }
                        }
                    else
                        if (oKhoahoc.iTrangthai == 2)
                        {
                            lblTrangthai.ForeColor = System.Drawing.ColorTranslator.FromHtml("#D14836");
                            lblTrangthai.Text = "Đã kết thúc";
                        }
                }

                btnDangky = (LinkButton)e.Row.Cells[8].Controls[0];
                if(btnDangky != null)
                {
                    if (bNamtrongkhoahoc(iGetUserLogin(), oKhoahoc.PK_iKhoahocID) != true)
                    {
                        if (oKhoahoc.iTrangthai > 0) //Đã bắt đầu học
                        {
                            btnDangky.Visible = false;
                        }
                        else
                        {
                            if (iGetUserLogin() > 0) //Nếu đã đăng nhập mới kiểm tra tình trạng đăng ký
                            {
                                if (DangkykhoahocBRL.GetByFK_iKhoahocIDAndFK_iHocvienID(oKhoahoc.PK_iKhoahocID, iGetUserLogin()) != null)
                                {
                                    btnDangky.CommandName = "Huydangky";
                                    btnDangky.Text = "Hủy đăng ký";
                                    btnDangky.CssClass = "button button-red";
                                }
                                else
                                {
                                    if (GlobalFunction.iSodangkyConlai(oKhoahoc.PK_iKhoahocID) > 0)
                                    {
                                        btnDangky.CommandName = "Dangky";
                                        btnDangky.Text = "Đăng ký";
                                        btnDangky.CssClass = "button button-blue";
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        btnDangky.CommandName = "Vaolop";
                        btnDangky.Text = "Vào lớp";
                        btnDangky.CssClass = "button button-red";
                    }
                }

                hplChitiet = (HyperLink)e.Row.FindControl("hplChitiet");
                if(hplChitiet != null)
                {
                    hplChitiet.Text = oKhoahoc.sTenkhoahoc;
                    hplChitiet.NavigateUrl = ResolveUrl("~/lop-hoc?id=" + oKhoahoc.PK_iKhoahocID);
                    hplChitiet.Target = "_bank";
                }
            }
            catch (Exception ex)
            {

            }
        }
    }
    protected void lbtnTimkhoahoc_Click(object sender, EventArgs e)
    {
        if (txtTimkiem.Text == "")
        {
            return;
        }
        String strTimkiem = txtTimkiem.Text;
        if (Cache["cacheLstGrvDatasource"] == null)
        {
            glbLstGrvDatasource = KhoahocBRL.GetAll();
            Cache["cacheLstGrvDatasource"] = glbLstGrvDatasource;
        }
        glbLstGrvDatasource = (List<KhoahocEntity>)Cache["cacheLstGrvDatasource"];

        glbLstGrvDatasource = glbLstGrvDatasource.FindAll
        (
            delegate(KhoahocEntity oKhoahocRes) 
            { 
                return (oKhoahocRes.sTenkhoahoc.Contains(strTimkiem) || oKhoahocRes.sGhichu.Contains(strTimkiem) || oKhoahocRes.sKyhieu.Contains(strTimkiem));
            }
        );

        grvDanhsachkhoahoc.DataSource = glbLstGrvDatasource;
        grvDanhsachkhoahoc.DataKeyNames = new string[] { "PK_iKhoahocID" };
        grvDanhsachkhoahoc.DataBind();
    }
    protected void lbtnHienthitatca_Click(object sender, EventArgs e)
    {
        Session["Khoahoccuatoi"] = false;
        glbLstGrvDatasource = KhoahocBRL.GetAll();
        Cache["cacheLstGrvDatasource"] = glbLstGrvDatasource;
        grvDanhsachkhoahoc.DataSource = glbLstGrvDatasource;
        grvDanhsachkhoahoc.DataKeyNames = new string[] { "PK_iKhoahocID" };
        grvDanhsachkhoahoc.DataBind();
    }
    protected void lbtnKhoahoccuatoi_Click(object sender, EventArgs e)
    {
        Session["Khoahoccuatoi"] = true;
        napGrvDanhsachkhoahoc(false);
    }
}